﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharpSoft.Documentation.Html.CSS
{
    public class CssBlockParser
    {
        public CssBlockParser(string source)
        {
            _Lexer = new CssBlockLexer(source);
        }
        public CssBlockParser(SharpSoft.Lexing.TextSource source)
        {
            _Lexer = new CssBlockLexer(source);
        }

        private readonly CssBlockLexer _Lexer;

        public CssData Parse()
        {
            List<CssBlockToken> list = new List<CssBlockToken>(2);
            while (true)
            {
                var t = _Lexer.ReadToken();
                if (t == null)
                    break;
                list.Add(t);
            }
            CssData d = new CssData();
            for (int i = 0; i < list.Count; i += 2)
            {
                var sel = list[i];
                if (sel.Type != BlockTokenType.Selector)
                    throw new CssSyntaxException(sel.Position, sel.Length);
                var pro = list[i + 1];
                if (pro.Type != BlockTokenType.PropertyBlock)
                    throw new CssSyntaxException(sel.Position, sel.Length);
                var sels = SelectorParser.Parse(sel.Content);
                var props = CssPropertiesParser.Parse(pro.Content);
                CssBlock block = new CssBlock("", sels, props);
                d.AddBlock(block);
            }
            return d;
        }

        public static CssData Parse(string source)
        {
            CssBlockParser p = new CssBlockParser(source);
            return p.Parse();
        
        }
    }
}
